package com.coalmine.api.config;

import com.coalmine.api.filter.ApiAuthFilter;
import com.coalmine.api.filter.ApiIPFilter;
import com.coalmine.api.servelt.APIServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class APIServletConfig {
    @Value("${datamanage.api.context}")
    String apiContext;

    @Autowired
    APIServlet APIServlet;

    //filter 会自动全局注册
    @Autowired
    ApiIPFilter apiIPFilter;

    @Autowired
    ApiAuthFilter apiAuthFilter;

    @Bean
    public ServletRegistrationBean getServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(APIServlet);
        bean.addUrlMappings(String.format("/%s/*", apiContext));
        bean.setName("APIServlet");
        return bean;
    }


    @Bean
    public FilterRegistrationBean IPFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(apiIPFilter);
        registrationBean.addUrlPatterns(String.format("/%s/*", apiContext));
        registrationBean.setOrder(1);
        registrationBean.setEnabled(true);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean authFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(apiAuthFilter);
        registrationBean.addUrlPatterns(String.format("/%s/*", apiContext));
        registrationBean.setOrder(2);
        registrationBean.setEnabled(true);
        return registrationBean;
    }
}
